using System;
using System.Collections.Generic;
using System.Text;

namespace ApplicationCore
{
    public static class  Statistics
    {

        public static double? Avg(double?[] measures)
        {
            double count = 0;
            double? ret = 0;
            foreach (double? m in measures)
            {
                if (m != null)
                {
                    ret += m;
                    count++;
                }
            }
            if (count > 0)
                return ret / count;
            else
                return null;
        }


        public static double? Median(double?[] measures)
        {
          double? ret = 0;
            
            List<double> temp = new List<double>();
            foreach (double? x in measures)
            {
                if (x != null)
                    temp.Add((double)x);
            }

            if (temp.Count < 1)
                ret = null;
            else
            {
                temp.Sort();
                if (temp.Count % 2 == 0)
                {
                    double x = temp[(temp.Count / 2)-1];
                   double y = temp[(temp.Count / 2)  ];
                    ret = (x + y) / 2;
                }
                else
                {
                    ret = temp[((temp.Count + 1) / 2)-1];
                }
            }
            return ret;
        }


        public static double? Stabw(double?[] measures)
        {
            double count = 0;
            double? ret = Avg(measures);
            if (ret == null)
                return null;
            double? diffs = 0;
            foreach (double? m in measures)
            {
                if (m != null)
                {
                    diffs += (m - ret) * (m - ret);
                    count++;
                }
            }
            ret = diffs / (count - 1);
            ret = Math.Sqrt((double)ret);
            return ret;
        }

        public static double? Error(double?[] measures)
        {
            double? avg = Avg(measures);
            if (avg == null)
                return null;
            double? stabw = Stabw(measures);
            double? ret = stabw / avg;
            ret = ret * 100;
            return ret;
        }

    }
}
